<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 商品分类 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="categoryName" placeholder="请输入商品分类名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="categoryOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="商品描述" prop="goodsDesc">
            <el-input v-model="queryParams.goodsDesc" placeholder="请输入商品描述" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="商品使用说明" prop="goodsInstructions">
            <el-input v-model="queryParams.goodsInstructions" placeholder="请输入商品使用说明" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="商品积分数" prop="goodsScore">
            <el-input v-model="queryParams.goodsScore" placeholder="请输入商品积分数" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="商品现金" prop="goodsMoney">
            <el-input v-model="queryParams.goodsMoney" placeholder="请输入商品现金" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['mall:goods:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['mall:goods:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['mall:goods:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['mall:goods:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="商品ID" align="center" prop="goodsId" v-if="true" />
          <el-table-column label="商品分类表主键" align="center" prop="categoryId" />
          <el-table-column label="商品名称" align="center" prop="goodsName" />
          <el-table-column label="" align="center" prop="goodsShortName" />
          <el-table-column label="图片地址" align="center" prop="goodsImg" />
          <el-table-column label="小图片地址" align="center" prop="goodsSmallImg" />
          <el-table-column label="大图片地址" align="center" prop="goodsBigImg" />
          <el-table-column label="商品描述" align="center" prop="goodsDesc" />
          <el-table-column label="商品使用说明" align="center" prop="goodsInstructions" />
          <el-table-column label="支付规则 (0：现金 1：积分 2：现金+积分）" align="center" prop="payRule" />
          <el-table-column label="商品积分数" align="center" prop="goodsScore" />
          <el-table-column label="商品现金" align="center" prop="goodsMoney" />
          <el-table-column label="商品状态" align="center" prop="goodsStatus" />
          <el-table-column label="删除标志(0：未删除 1：已删除)" align="center" prop="yn" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['mall:goods:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['mall:goods:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加商品规格列表 -->
    <el-dialog :title="GoodsSpecificationsTitle" :visible.sync="openGoodsSpec" width="700px" append-to-body>
      <el-form ref="SpecificationsForm" :model="SpecificationsForm" :rules="rules" label-width="80px">
        <el-row>
          <el-table v-loading="loading" :data="specificationsList" @selection-change="handleSelectionChange">
            <el-table-column label="商品规格表主键ID" align="center" prop="goodsSpecificationsId" v-if="true" />
            <el-table-column label="商品规格名称" align="center" prop="name">
            </el-table-column>
            <el-table-column label="商品规格描述" align="center" prop="desc" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAddGoodsSpec(scope.row)"
                  v-hasPermi="['mall:specifications:edit']">添加规格</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 添加或修改商城商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="商品分类" prop="categoryId">
            <el-tag size="medium">{{ selectCategory.label }}</el-tag>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品简称" prop="goodsShortName">
              <el-input v-model="form.goodsShortName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="图片地址" prop="goodsImg">
              <ImageUpload @success="uploadImg" :limit="1" :value="form.goodsImg" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="小图片地址" prop="goodsSmallImg">
              <ImageUpload @success="uploadSmallImg" :limit="1" :value="form.goodsSmallImg" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="大图片地址" prop="goodsBigImg">
              <ImageUpload @success="uploadBigImg" :limit="1" :value="form.goodsBigImg" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="商品描述" prop="goodsDesc">
            <el-input v-model="form.goodsDesc" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="使用说明" prop="goodsInstructions">
            <el-input v-model="form.goodsInstructions" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付规则" prop="payRule">
              (0：现金 1：积分 2：现金+积分）
              <el-select v-model="selectedPayValue" @change="handleSelectChangePayRule" placeholder="请选择商品状态">
                <el-option v-for="item in goodsPayRuleOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品积分" prop="goodsScore">
              <el-input v-model="form.goodsScore" placeholder="请输入商品积分数" />
            </el-form-item> </el-col></el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品价格" prop="goodsMoney">
              <el-input v-model="form.goodsMoney" placeholder="请输入商品价格" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品状态" prop="goodsStatus">
              <el-select v-model="selectedValue" @change="handleSelectChange" placeholder="请选择商品状态">
                <el-option v-for="item in goodsStatusOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item> </el-col></el-row>
        <el-row>
          <el-form-item label="商品规格列表" prop="goodsDesc">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddSpec()">新增</el-button>
            <el-table :data="form.lstGoodsSpecifications" :border="true" :show-header="true">
              <el-table-column label="规格名称" prop="name" width="150" align="center" />
              <el-table-column label="规格描述" prop="desc" width="150" align="center" />
              <el-table-column label="操作" width="100" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete"
                    @click="handleDeleteSpec(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  categoryTree,
} from "@/api/mall/goods";
import { listSpecifications } from "@/api/mall/specifications";

export default {
  name: "Goods",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商城商品信息表格数据
      goodsList: [],
      // 商品分类树选项
      categoryOptions: undefined,
      categoryName: "",
      // 商品分类树选中值
      selectedValue: 0,
      //商品支付类型选中值
      selectedPayValue: 0,
      defaultProps: {
        children: "children",
        label: "label",
      },
      GoodsSpecificationsTitle: "商品规格列表",
      // 商品规格列表
      specificationsList: [],
      // 弹出层是否显示
      openGoodsSpec: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //选中商品分类ID
      selectCategory: {},
      goodsStatusOptions: [
        { label: "上架", value: 0 },
        { label: "下架", value: 1 },
      ],
      goodsPayRuleOptions: [
        { label: "现金", value: 0 },
        { label: "积分", value: 1 },
        { label: "现金+积分", value: 2 },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,
        goodsName: undefined,
        goodsShortName: undefined,
        goodsImg: undefined,
        goodsSmallImg: undefined,
        goodsBigImg: undefined,
        goodsDesc: undefined,
        goodsInstructions: undefined,
        payRule: undefined,
        goodsScore: undefined,
        goodsMoney: undefined,
        goodsStatus: undefined,
        yn: undefined,
      },
      // 表单参数
      form: {},
      SpecificationsForm: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        payRule: [
          {
            required: true,
            message: "支付规则 (0：现金 1：积分 2：现金+积分）不能为空",
            trigger: "blur",
          },
        ],
        goodsScore: [
          { required: true, message: "商品积分数不能为空", trigger: "blur" },
        ],
        goodsMoney: [
          { required: true, message: "商品价格不能为空", trigger: "blur" },
        ],
        goodsStatus: [
          { required: true, message: "商品状态不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCategoryTree();
  },
  methods: {
    /** 查询商城商品信息列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询商品分类下拉树结构 */
    getCategoryTree() {
      categoryTree().then((response) => {
        this.categoryOptions = response.data;
      });
    },
    handleSelectChange(row) {
      if (row != null) {
        this.form.goodsStatus = row;
      }
    },
    handleSelectChangePayRule(row) {
      if (row != null) {
        this.form.payRule = row;
      }
    },
    handleAddGoodsSpec(row) {
      if (this.form.lstGoodsSpecifications == null) {
        this.form.lstGoodsSpecifications = [];
      }
      var found = false;
      this.form.lstGoodsSpecifications.forEach((element) => {
        if (element.goodsSpecificationsId == row.goodsSpecificationsId) {
          found = true;
        }
      });
      if (!found) {
        this.form.lstGoodsSpecifications.push(row);
        this.openGoodsSpec = false;
      } else {
        this.$message.error("该规格已添加");
      }
    },
    handleAddSpec() {
      this.openGoodsSpec = true;
      listSpecifications().then((response) => {
        this.specificationsList = response.rows;
      });
    },
    handleDeleteSpec(row) {
      for (let i = this.form.lstGoodsSpecifications.length - 1; i >= 0; i--) {
        if (
          this.form.lstGoodsSpecifications[i].goodsSpecificationsId ==
          row.goodsSpecificationsId
        ) {
          this.form.lstGoodsSpecifications.splice(i, 1);
          break;
        }
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.selectCategory = data;
      this.queryParams.categoryId = data.id;
      this.handleQuery();
    },
    uploadImg(file) {
      this.form.goodsImg = file;
    },
    uploadSmallImg(file) {
      this.form.goodsSmallImg = file;
    },
    uploadBigImg(file) {
      this.form.goodsBigImg = file;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: undefined,
        categoryId: undefined,
        goodsName: undefined,
        goodsShortName: undefined,
        goodsImg: undefined,
        goodsSmallImg: undefined,
        goodsBigImg: undefined,
        goodsDesc: undefined,
        goodsInstructions: undefined,
        payRule: undefined,
        goodsScore: undefined,
        goodsMoney: undefined,
        goodsStatus: undefined,
        yn: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        lstGoodsSpecifications: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.goodsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.selectCategory.id == null || this.selectCategory.id == undefined) {
        this.$message.error("请选择商品分类");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加商城商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const goodsId = row.goodsId || this.ids;
      getGoods(goodsId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改商城商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.goodsId != null) {
            updateGoods(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addGoods(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$modal
        .confirm('是否确认删除商城商品信息编号为"' + goodsIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delGoods(goodsIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mall/goods/export",
        {
          ...this.queryParams,
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
